/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package es.srn.utils.plantillas;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import es.srn.ipartek.ejemplo01.ClsAlumno;
import es.srn.utils.ClsUtilsNumeros;


/**
 *
 * @author Sergio Rubio
 */
public class ClsMyFTPObjFicherosOrigenXML 
{
    
    //Acciones a realizar sobre los hostnames
  public enum eAction
  {
      NONE,
      ADD,
      DELETE,
      UPDATE
  }
  
  
  static final String ITEM = "item";
  
  //HOSTNAMES
  static final String NOMBRE = "nombre";
  static final String APELLIDO1 = "apellido1";
  static final String APELLIDO2 = "apellido2";
  static final String EDAD = "edad";


  
  private static List<ClsAlumno> items = new ArrayList<>();       
  
  //HOSTNAMES
  //@SuppressWarnings({ "unchecked", "null" })
  public static List<ClsAlumno> readHostnames(String configFile) throws FileNotFoundException, XMLStreamException{
    try {
        
        items.clear();
        
      // First, create a new XMLInputFactory
      XMLInputFactory inputFactory = XMLInputFactory.newInstance();
      // Setup a new eventReader
      InputStream in = new FileInputStream(configFile);
      XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
      // readclsAlumnodocument
      ClsAlumno item = null;

      while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();

        if (event.isStartElement()) {
          StartElement startElement = event.asStartElement();
          // If we have an item element, we create a new item
          if (startElement.getName().getLocalPart().equalsIgnoreCase(ITEM)){            
            item = new ClsAlumno();
            // We read the attributes from this tag and add the date
            // attribute to our object
            Iterator<Attribute> attributes = startElement
                .getAttributes();
            while (attributes.hasNext()) {
              Attribute attribute = attributes.next();
              if (attribute.getName().toString().equalsIgnoreCase(NOMBRE)) {
                item.setNombre(attribute.getValue());
              }
            }
          }

          if (event.isStartElement()) {
            if (event.asStartElement().getName().getLocalPart()
                .equalsIgnoreCase(APELLIDO1)) {
              event = eventReader.nextEvent();
              item.setApellido1(event.asCharacters().getData());
              continue;
            }
          }
          if (event.asStartElement().getName().getLocalPart()
              .equalsIgnoreCase(APELLIDO2)) {
            event = eventReader.nextEvent();
            item.setApellido2(event.asCharacters().getData());
            continue;
          }

         

          if (event.asStartElement().getName().getLocalPart()
              .equalsIgnoreCase(EDAD)) {
            event = eventReader.nextEvent();
            String puerto = event.asCharacters().getData();
            if(!puerto.equals("") && ClsUtilsNumeros.isNumeric(puerto) )
            {
                item.setEdad(Integer.parseInt(puerto));
            }            
            continue;
          }
          
          
        }        
        
        // If we reach the end of an item element, we add it to the list
        if (event.isEndElement()) {
          EndElement endElement = event.asEndElement();
          if (endElement.getName().getLocalPart().equalsIgnoreCase(ITEM)) {
            items.add(item);
          }
        }

      }
    } catch (FileNotFoundException | XMLStreamException e) {
      e.printStackTrace();
      throw e;
    }
    return items;
  }
    
  
  
  
  
  public static void ejecutar(String configFile,String identificador, ClsAlumno hostname, eAction accion)
  {      
    String filePath = configFile;
    File xmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    
    try{
        
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();

        switch (accion)
        {
            case ADD:
                addElement(doc,hostname);
                break;
            case DELETE:
                deleteElement(doc, hostname);
                break;
            case UPDATE:
                break;
			default:
				break;
        }
                
        //write the updated document to file or console
        doc.getDocumentElement().normalize();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(configFile));
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(source, result);
        System.out.println("XML file updated successfully");
    } catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {
            e1.printStackTrace();
    }
  }
    
    private static void addElement(Document doc, ClsAlumno hostname) {

        //creamos el nodo principal
        Element nodePrincipal = doc.createElement(ITEM);
        nodePrincipal.setAttribute(NOMBRE, hostname.getNombre());
        
        Element eNombre = doc.createElement(APELLIDO1);
        eNombre.appendChild(doc.createTextNode(hostname.getApellido1()));        
        nodePrincipal.appendChild(eNombre);
        
        Element eUser = doc.createElement(APELLIDO2);
        eUser.appendChild(doc.createTextNode(hostname.getApellido2())); 
        nodePrincipal.appendChild(eUser);
        
        Element ePassword = doc.createElement(EDAD);
        ePassword.appendChild(doc.createTextNode(String.valueOf(hostname.getEdad()) )); 
        nodePrincipal.appendChild(ePassword);        
        
        
        doc.getDocumentElement().appendChild(nodePrincipal);       
    }

    private static void deleteElement(Document doc, ClsAlumno hostname) {
        NodeList lstNodes = doc.getElementsByTagName(ITEM);
        Element emp = null;
        Element remove = null;
        
        for (int i = 0; i < lstNodes.getLength(); i++) {
            emp = (Element) lstNodes.item(i);
            String atributo = emp.getAttribute(NOMBRE);
            if(atributo.equalsIgnoreCase(hostname.getNombre()))
            {
                remove = emp;
            }
        }
        
        if(remove != null)
        {
            doc.getDocumentElement().removeChild(remove);
            
        }
    }
    
    private static void updateElement(Document doc,String nombre, ClsAlumno hostname)
    {
        NodeList lstNodes = doc.getElementsByTagName(ITEM);
        Element emp = null;
        Element update = null;
        
       for (int i = 0; i < lstNodes.getLength(); i++) {
            emp = (Element) lstNodes.item(i);
            String atributo = emp.getAttribute(NOMBRE);
            if(atributo.equalsIgnoreCase(nombre))
            {
                update = emp;
            }
        }       
       
       if(update != null)
       {
          update.setAttribute(NOMBRE, hostname.getNombre());
          
          Node hostName = update.getElementsByTagName(NOMBRE).item(0).getFirstChild();
          hostName.setNodeValue(hostname.getNombre());
       }
    }

    private static void updateElementValue(Document doc) {
        NodeList employees = doc.getElementsByTagName(ITEM);
        Element emp = null;
        //loop for each employee
        for (int i = 0; i < employees.getLength(); i++) {
            emp = (Element) employees.item(i);
            Node name = emp.getElementsByTagName("name").item(0).getFirstChild();
            name.setNodeValue(name.getNodeValue().toUpperCase());
        }
    }

    private static void updateAttributeValue(Document doc) {
        NodeList employees = doc.getElementsByTagName(ITEM);
        Element emp = null;
        //loop for each employee
        for (int i = 0; i < employees.getLength(); i++) {
            emp = (Element) employees.item(i);
            String gender = emp.getElementsByTagName("gender").item(0).getFirstChild().getNodeValue();
            if (gender.equalsIgnoreCase("male")) {
                //prefix id attribute with M
                emp.setAttribute("id", "M" + emp.getAttribute("id"));
            } else {
                //prefix id attribute with F
                emp.setAttribute("id", "F" + emp.getAttribute("id"));
            }
        }
    }

}
